package com.xinshujia.listener;

import com.xinshujia.entity.QuartzEntity;
import com.xinshujia.service.QuartzService;
import com.xinshujia.utils.ConstantsUtil;
import org.quartz.Scheduler;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-23 14:20       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
@Component
public class MyListener implements ApplicationListener<ApplicationReadyEvent> {
    private final Scheduler scheduler;
    private final QuartzService quartzService;

    public MyListener(Scheduler scheduler, QuartzService quartzService) {
        this.scheduler = scheduler;
        this.quartzService = quartzService;
    }
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 获取所有的定时任务
        List<QuartzEntity> quartzEntities = quartzService.getQuartzs();
        for (QuartzEntity quartzEntity : quartzEntities) {
            if(quartzEntity.getStatus().equals(ConstantsUtil.QUARTZ_STATUS_RUNNING)){
                // 创建定时任务
                try {
                    quartzService.createJob(scheduler, quartzEntity);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        }

        System.out.println("MyListener执行了初始化逻辑");
    }
}
